<?php


/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/**
 * @package	
 */
class HelpDeskModelCategories extends HelpDeskModel 
{
	/**
	 * constructor
	 * @return array Array of objects containing the data from the category
	 */	
	function __construct() {
		
	}

/**
	 * Returns the query
	 * @return string The query to be used to retrieve the rows from the database
	 */
	function _buildQuery() 
	{
		$database 	= &HelpDeskConfig::getDBO();
		$user 		= &HelpDeskConfig::getUser();
		$config 	= &HelpDeskConfig::getInstance();

		// parentid
			$parentid = $this->getField( $config->getFieldname( 'parentid' ) );
			$parentid_query = "";
			if (intval($parentid) > 0) {
				$parentid_query = " AND db.parentid = '" . trim( strtolower( $parentid ) ) . "'";
			} elseif (intval($parentid) == '-1') {
				$parentid_query = " AND db.parentid = '0'";
			}

		// publishedid
			$publishedid = $this->getField( $config->getFieldname( 'publishedid' ) );
			$publishedid_query = "";
			if (intval($publishedid) == '1') {
				$publishedid_query = " AND db.published = '" . trim( strtolower( $publishedid ) ) . "'";
			} elseif (isset($publishedid) && $publishedid == '0') {
				$publishedid_query = " AND db.published = '0'";
			}
			
		// search
			$where = array();
			$search	= $this->getField( $config->getFieldname( 'search' ) );
			if (isset($search)) 
			{
				$where[] = " LOWER(db.id) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
				$where[] = " LOWER(db.title) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
				$where[] = " LOWER(db.description) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
			}
			$where_query = count( $where ) ? "\n HAVING " . implode( ' OR ', $where ) : "";
						
		// order
			$order_query = "";
			$order = $this->getState( 'order' );
			$order_dir = $this->getState( 'order_dir' );
			switch ($order) 
			{
				case "parentid":
					$order_query = " ORDER BY db.parentid ".strtoupper( $order_dir )." ";
				  break;
				case "order":
				case "ordering":
					$order_query = " ORDER BY db.ordering ".strtoupper( $order_dir )." ";
				  break;
				case "title":
					$order_query = " ORDER BY db.title ".strtoupper( $order_dir )." ";
				  break;
				case "published":
					$order_query = " ORDER BY db.published ".strtoupper( $order_dir )." ";
				  break; 
				case "id":
				default:
					$order_query = " ORDER BY db.id ".strtoupper( $order_dir )." ";
				  break;
			}

		// build query
			$query = "
				SELECT 
					db.* 
				FROM 
					#__helpdesk_categories as db
				WHERE 1
					{$parentid_query}
					{$publishedid_query}
					{$where_query} 
				{$order_query}
			";

		return $query;
	}

	/**
	 * 
	 * @return unknown_type
	 */
	function save()
	{
		//		$mainframe 	= HelpDeskConfig::getApplication();
		//		$database 	= HelpDeskConfig::getDBO();
		//		$date 		= HelpDeskConfig::getDate();

		// bind the entry
	    $row = $this->getTable('category');	
	    $row->load( $this->getId() );	
		$row->bind($_POST);
		
		// invalid entries
		// TODO Push this to table definition and start using check()
		if ( !$row->title ) {
        	$this->setError( HelpDeskText::_( 'Title is Required' ) );
        	return false;
		}

   		// Store the entry
    	if (!$row->store()) {
        	$this->setError( $row->getErrorMsg() );
        	return false;
    	}
		
		return $row;
	}
		
	/**
	 * Method to delete record(s)
	 *
	 * @access    public
	 * @return    boolean    True on success
	 */
	function delete( &$msg )
	{
		$cids = HelpDeskRequest::getVar('cid', array (0), 'post', 'array');
		$row = $this->getTable( 'category' );

		foreach ($cids as $cid)
		{
			if (!$row->delete($cid))
			{
				$msg->message .= $row->getErrorMsg(); 
				$msg->type = 'notice';
			}
		}

		return true;
	}
	
	/**
	 * 
	 *
	 * @access    public
	 * @return    boolean    True on success
	 */
	function publish( &$msg )
	{
		$success = true;
		$cids 	= HelpDeskRequest::getVar('cid', array (0), 'post', 'array');
		$row 	= $this->getTable( 'category' );
		
		$task = HelpDeskRequest::getVar( 'task' );
		switch (strtolower($task))
		{
			case "switch":
			case "switch_publish":
				$switch = '1';
			  break;
			case "unpublish":
				$publish = '0';
				$switch = '0';
			  break;
			case "publish":
			default:
				$publish = '1';
				$switch = '0';
			  break;
		}

		foreach ($cids as $cid)
		{
			$row->load( $cid );
			
			switch ($switch)
			{
				case "1":
					// do switch
					$row->published = $row->published ? '0' : '1';
				  break;
				case "0":
				default:
					$row->published = $publish;
				  break;
			}
			
			if (!$row->store())
			{
				$msg->message .= $row->getErrorMsg(); 
				$msg->type = 'notice';
				$success = false;
			}
			
		}

		return $success;
	}
	
	/**
	 *
	 * @access    public
	 * @return    boolean    True on success
	 */
	function saveorder( &$msg )
	{
		$success 	= true;
		
		$cids 		= HelpDeskRequest::getVar('cid', array(0), 'post', 'array');
		$ordering 	= HelpDeskRequest::getVar('ordering', array(0), 'post', 'array');
		$row 		= $this->getTable( 'category' );
		
		foreach ($cids as $cid)
		{
			$row->load( $cid );
			$row->ordering = @$ordering[$cid];
			
			if (!$row->store())
			{
				$msg->message .= $row->getErrorMsg(); 
				$msg->type = 'notice';
				$success = false;
			}
		}

		return $success;
	}
	
	
	/**
	 * 
	 *
	 * @access    public
	 * @return    boolean    True on success
	 */
	function switch_define( &$msg )
	{
		$success = true;
		$result = array();
		$errors = array();
		$cids 	= HelpDeskRequest::getVar('cid', array (0), 'post', 'array');
		$id = HelpDeskRequest::getVar( 'id' );
		
		foreach ($cids as $cid)
		{
			$already = HelpDeskHelperCategory::isManager( $id, $cid );
			if ($already) 
			{
				if (!$act = HelpDeskHelperCategory::removeManager( $id, $cid ))
				{
					// $msg->message .= HelpDeskText::_( "Could Not Remove From" );
					$result[] = false;
					$errors[$cid] = $cid; 	
				}
				
			} else {
				if (!$act = HelpDeskHelperCategory::addManager( $id, $cid ))
				{
					$result[] = false;
					$errors[$cid] = $cid; 	
				}
			}
		}
		
		if (in_array(false, $result, true)) {
			$msg->type = 'notice';
			$msg->message .= HelpDeskText::_( 'Could Not Switch' ) . ' ' . implode( ' & ', $errors );
			$success = false;
		}

		return $success;
	}

}